import NodeForm from "./node_form";

export const generalMixin = {
  props: {
    formSetting: {
      type: Object,
      default: () => {
        return {};
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {
        return {};
      }
    },
    node: {
      type: Object,
      default: () => {
        return {};
      }
    },
    jsPlumb: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  components: {
    NodeForm
  },
  watch: {
    visible(val) {
      if (val) {
        this.nodeInit()
      }
    }
  },
  data() {
    return {
    };
  },
  methods: {
    validateForm() {
      const { id, type } = this.node;
      const refFlowForm = this.$refs[`${type}FlowForm`];
      refFlowForm.$refs[`form`].validate(async valid => {
        if (valid) {
          const { status, message } = this.validateDrawerForm();
          if (status === "error") {
            return this.$message.error(message);
          }
          const { name } = this.$refs.NodeForm["nodeForm"];
          const paramsForm =
            refFlowForm[`form`] || refFlowForm[`searchData`] || {}; // 兼容一下特殊情况群组Form
          this.$set(this.formSetting, id, { ...paramsForm, name });
          this.data.nodeList.filter(node => {
            if (node.id === id) {
              node.name = name;
              this.$emit("repaintEverything");
              this.cancel()
            }
          });
        }
      });
    },
    /**
     * 表单修改，这里可以根据传入的node的ID进行业务信息获取
     * @param data
     * @param node
     */
    async nodeInit() {
      const { id, name, type } = this.node;
      await this.$nextTick();
      this.$refs.NodeForm.nodeFormInit(name);
      this.$refs[`${type}FlowForm`].init(this.formSetting[id]);
    },
    validateDrawerForm() {
      const { nodeList } = this.data;
      const { id } = this.node;
      const { name } = this.$refs.NodeForm["nodeForm"];
      const nameArr = nodeList
        .filter(ele => ele.id !== id)
        .map(ele => ele["name"]);
      if (nameArr.includes(name)) {
        return { status: "error", message: "节点名称重复" };
      }
      return { status: "ok", message: "ok" };
    },
    save() {
      const FlowNodeForm = this.$refs.NodeForm;
      FlowNodeForm.$refs.nodeForm.validate(async valid => {
        if (valid) {
          this.validateForm();
        }
      });
    },
    cancel() {
      this.$emit('update:visible', false)
    }
  }
};
